package com.superpet.weixin.api.wxrun;

import com.superpet.common.kits.DateKit;
import com.superpet.common.kits.NumberKit;
import com.superpet.common.model.WxRun;

import java.text.ParseException;

public class WxRunService {

    public static final WxRunService me = new WxRunService();

    public WxRun getWxRunByOpenidAndTimestamp(String openid, Long timestamp){
        return WxRun.dao.findFirst("select * from p_wx_run where openid=? and timestamp=? limit 1"
                , openid, timestamp);
    }

    public void saveOrUpdateWxRun(WxRun wxRun){
        WxRun saveWxRun = getWxRunByOpenidAndTimestamp(wxRun.getOpenid(),wxRun.getTimestamp());
        if(saveWxRun==null){
            saveWxRun = new WxRun();
            saveWxRun.setOpenid(wxRun.getOpenid());
            saveWxRun.setStep(wxRun.getStep());
            saveWxRun.setStepRemain(wxRun.getStep());
            saveWxRun.setTimestamp(wxRun.getTimestamp());
            saveWxRun.save();
        }else{
            saveWxRun.setStepRemain(wxRun.getStep()-saveWxRun.getStep()+saveWxRun.getStepRemain());
            saveWxRun.setStep(wxRun.getStep());
            saveWxRun.update();
        }
    }

    public Integer getWxRunForFeed(String openid, String date) throws ParseException {
        Long dates = DateKit.strToDate(date).getTime();
        WxRun wxRun = this.getWxRunByOpenidAndTimestamp(openid,dates);
        Integer remainFeedTimes = wxRun.getFeedTimesTotal()-wxRun.getFeedTimes();
        Integer feedVal = -2;
        if(remainFeedTimes==1){//last times
            feedVal = wxRun.getStepRemain();
            wxRun.setStepRemain(0);
            wxRun.setFeedTimes(wxRun.getFeedTimes()+1);
            wxRun.update();
        }else if(remainFeedTimes>1 && wxRun.getStepRemain()>0){ // wxRun.getStepRemain()==0表示没有运动步数，这里可以进一步细化提示信息
            Integer steps = NumberKit.getRandom(wxRun.getStepRemain());
            wxRun.setStepRemain(wxRun.getStepRemain()-steps);
            wxRun.setFeedTimes(wxRun.getFeedTimes()+1);
            wxRun.update();
            feedVal = steps;
        }else if(wxRun.getStep()==0 && wxRun.getStepRemain()==0){//昨天没有运动步数的用户
            feedVal = -1;
        }
        return feedVal;
    }

    public Integer getWxRunForFeedMyself(String openid, String date) throws ParseException {
        Long dates = DateKit.strToDate(date).getTime();
        WxRun wxRun = this.getWxRunByOpenidAndTimestamp(openid,dates);
        Integer feedVal = wxRun.getStep();
        if(wxRun.getStep()==0 && wxRun.getStepRemain()==0){//昨天没有运动步数的用户
            feedVal = -1;
        }
        return feedVal;
    }
}
